package com.jingfu.configuration;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.Environment;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;

import java.io.IOException;

/**
 * 	 为了规避Spring xml配置方式，无法通过 Environment获得属性值
 * 	 只能手工添加应用配置对应的 PropertySource到Environment里以解决问题
 * @author jingfuu@163.com
 * @version v1.0
 * @date 2022/1/14 下午5:19
 **/
public class MyPropertySourcesPlaceholderConfigurer extends PropertySourcesPlaceholderConfigurer {
    private Environment environ;

    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        ConfigurableEnvironment env = null;
        super.postProcessBeanFactory(beanFactory);
        if (this.environ != null) {
            if (environ instanceof ConfigurableEnvironment){
                env = (ConfigurableEnvironment)environ;
            }
            if (env != null) {
                PropertySource<?> localPropertySource = null;
                try {
                    localPropertySource = new PropertiesPropertySource("localProperties", super.mergeProperties());
                } catch (IOException e) {
                    e.printStackTrace();
                }
                env.getPropertySources().addLast(localPropertySource);
            }
        }

    }

    @Override
    public void setEnvironment(Environment environment) {
        super.setEnvironment(environment);
        this.environ = environment;
    }
}
